package com.xujl.hsns.codec.impl;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dyuproject.protostuff.XmlIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

public class XMLDecoder extends CumulativeProtocolDecoder {
	private final static Logger LOGGER = LoggerFactory.getLogger(XMLDecoder.class);
	Schema schema;
	Class decodeClazz;
	public  XMLDecoder (Class decodeClazz){
		 this.decodeClazz= decodeClazz;
		 schema=RuntimeSchema.createFrom(decodeClazz);
	}
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		if (in.prefixedDataAvailable(4)) { 
            int length = in.getInt(); 
            byte[] bytes = new byte[length]; 
            in.get(bytes);
            LOGGER.debug("bytes length:"+length);
            Object o=decodeClazz.newInstance();
        	
            XmlIOUtil.mergeFrom(bytes, o, schema);
			
			LOGGER.info(o.getClass().toString());
            out.write(o); 
           
            return true; 
        } else { 
            return false; 
        }
	}

}
